package com.ybkj.daijia.server.scheduler;

import static com.ybkj.daijia.DateTimeUtils.MINUTE_MILLISECONDS;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ybkj.daijia.DateTimeUtils;
import com.ybkj.daijia.RestTemplateUtils;
import com.ybkj.daijia.ServiceSetting;
import com.ybkj.daijia.Setting;
import com.ybkj.daijia.common.Result;
import com.ybkj.daijia.config.ZhuanApi;
import com.ybkj.daijia.server.service.ZhuancheService;
import com.ybkj.daijia.server.service.ZhuanxianService;
import com.ybkj.daijia.server.zhuan.Order;
import com.ybkj.daijia.serverUtils.ServiceUtil;
import com.ybkj.daijia.serverUtils.SettingUtils;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author UG
 */

@Component
@Slf4j
public class AutoCancelOrder {


    @Autowired
    private SettingUtils settingUtils;
    @Autowired
    private ZhuancheService zhuancheService;
    @Autowired
    private ZhuanxianService zhuanxianService;
    @Autowired
    private RestTemplateUtils restTemplateUtils;
    @Autowired
    private ZhuanApi zhuanApi;

    private ServiceSetting serviceSetting = ServiceUtil.checkOpen();

    private Long zhuanXianAutoCancelOrderTime = DateTimeUtils.HOUR_MILLISECONDS;
    private Long kuaicheAutoCancelOrderTime = DateTimeUtils.HOUR_MILLISECONDS;

    @Transactional(rollbackFor = Exception.class)
    public void check() {
        Setting setting = settingUtils.get();
        if (serviceSetting.isZhuanche() && setting.isKuaicheAutoCancelOrder()) {
            Integer time = setting.getKuaicheAutoCancelOrderTime();
            if (time != null) {
                this.kuaicheAutoCancelOrderTime = Long.valueOf(time);
            }
            checkZhuanche();
        }
        if (serviceSetting.isZhuanxian() && setting.isZhuanxianAutoCancelOrder()) {
            Integer time = setting.getZhuanXianAutoCancelOrderTime();
            if (time != null) {
                this.zhuanXianAutoCancelOrderTime = Long.valueOf(time);
            }
            checkZhuanXian();
        }
    }

    public void checkZhuanche() {
        Map<String, Object> params = new HashMap<>(2);
        params.put("minuteTime", settingUtils.get().getKuaicheAutoCancelOrderTime()/ MINUTE_MILLISECONDS);
        restTemplateUtils.addAppKey(params);
        try {
            JSONObject json = restTemplateUtils.getRequestForJsonObject(params,zhuanApi.getZhuanBaseURL() + ZhuanApi.GET_OVERTIME_ORDERS);
            if (json.getInteger("code").equals(new Integer(0))) {
                String data = json.getString("data");
                if (StringUtils.isNotBlank(data)) {
                    List<Order> orders = JSON.parseArray(data, Order.class);
                    if (orders.size() > 0) {
                        for (Order order : orders) {
                            Result<Order> result = zhuancheService.cancelOrder(order, "新订单超时, 系统自动销单", "系统", "system");
                            if (result.isSuccess()) {
                                if (log.isInfoEnabled()) {
                                    log.info("新订单{} 超时, 系统自动销单", order.getOrderNo());
                                }
                                String remove = null;
                                for (String key : ThreadControl.TaskMaps.keySet()) {
                                    if (key.equals("task_" + order.getId())) {
                                        remove = "task_" + order.getId();
                                        break;
                                    }
                                }
                                if (remove != null) {
                                    Timer timer = ThreadControl.TaskMaps.remove(remove);
                                    timer.cancel();
                                }
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            if (log.isErrorEnabled()) {
                log.error("error", e);
            }
        }
    }

    public void checkZhuanXian() {
        List<com.ybkj.daijia.server.zhuanxian.Order> orderList = zhuanxianService.findByStatus(0);
        for (com.ybkj.daijia.server.zhuanxian.Order order : orderList) {
            if ((System.currentTimeMillis() - order.getUpdated().getTime()) > zhuanXianAutoCancelOrderTime) {
                zhuanxianService.cancelOrder(order, "订单派单超时，自动销单", "后台系统");
            }
        }
    }
}
